package com.idea.zd.sys.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WordUtil{

    public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件统一放至 com.lun.template 包下面
            System.out.println(System.getProperty("user.dir"));
            configuration.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir")+"/src/main/resources/template/"));

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath+File.separator+fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
        File file = new File(System.getProperty("user.dir")+"/src/main/resources/template/地面值班日志.docx");
        try {
            XWPFDocument doc = new XWPFDocument(new FileInputStream(file));
            XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
            List<XWPFParagraph> paragraph=  doc.getParagraphs();

            Iterator<XWPFParagraph> it = paragraph.iterator();
            while(it.hasNext()){
                XWPFParagraph XwpfParagrapg = it.next();
                System.out.println(XwpfParagrapg.getText());
                XwpfParagrapg.getElementType();
            }


            List<XWPFTable> xwpfTables = doc.getTables();
            for(XWPFTable xwpfTable : xwpfTables){
                List<XWPFTable> xwpfTables2 = xwpfTables;
                System.out.println(xwpfTable.getText());


            }



            //System.out.println(extractor.getText());
            extractor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //buffer = ex.getText();

    }

}
